<?php
/**
 * 
 * Enter description here ...
 * @author mcyami
 *
 */
namespace Org\Net;
class Online {
	
	protected $lifeTime = '1800', $sessionid = '', $dao;
	
	/**
	 * 初始化构造
	 */
	public function __construct(&$params = '') {
		$this->lifeTime = C ( 'EXPIRE_TIME' ) ? C ( 'EXPIRE_TIME' ) : 1800;
		
		if (cookie ( 'onlineid' )) {
			$this->sessionid = cookie ( 'onlineid' );
		} else {
			$this->sessionid = substr ( MD5 ( session_id () ), 0, 32 );
			cookie ( 'onlineid', $this->sessionid, 0 );
		}
		$this->dao = M ( 'Online' );
		//session_set_save_handler(array(&$this,'open'), array(&$this,'close'), array(&$this,'read'), array(&$this,'write'), array(&$this,'destroy'), array(&$this,'gc'));
		
		$this->write ( $this->sessionid );
		$this->gc ( $this->lifeTime );
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $savePath
	 * @param unknown_type $sessName
	 */
	public function open($savePath, $sessName) {
		return true;
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public function close() {
		return $this->gc ( $this->lifetime );
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $sessID
	 */
	public function read($sessID) {
		$r = $this->dao->find ( $sessID );
		return $r ? $r ['data'] : '';
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $sessID
	 * @param unknown_type $sessData
	 */
	public function write($sessID, $sessData) {
		$ip = get_client_ip ();
		$username = cookie ( 'musername' ) ? cookie ( 'musername' ) : '';
		$groupid = cookie ( 'mgroupid' ) ? intval ( cookie ( 'mgroupid' ) ) : 4;
		$sessiondata = array ('sessionid' => $sessID, 'userid' => intval ( cookie ( 'muserid' ) ), 'username' => $username, 'ip' => $ip, 'lastvisit' => time (), 'groupid' => $groupid, 'data' => '' );
		return $this->dao->add ( $sessiondata, '', true );
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $sessID
	 */
	public function destroy($sessID) {
		return $this->dao->delete ( $this->sessionid );
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $sessMaxLifeTime
	 */
	public function gc($sessMaxLifeTime) {
		$expiretime = time () - $sessMaxLifeTime;
		$r = $this->dao->where ( " lastvisit < $expiretime" )->delete ();
		return $r;
	}

}